﻿using System;
using System.IO;
using System.Xml;
using System.Configuration;
using System.Web;
using SyCODE.Component.DataFactory;
using System.Collections.Specialized;
using SyCODE.Component.Security;
using SyCODE.Component;
using System.Web.Security;

/// <summary>
/// SyCODE 的摘要说明
/// </summary>
namespace SyCODE.Blog
{
    public class SetFriendLink : IHttpHandler
    {        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
			Ticket ticket = Ticket.Get(FormsAuthentication.FormsCookieName);
            if (Ticket.Authenticate(ticket))
            {
                NameValueCollection nvc = new NameValueCollection(context.Request.Form);

                string path = Path.Combine(AppPath.GetUserPhysicalPath(ticket.Name), "link.xml");

                XmlDocument linkDom = new XmlDocument();
                linkDom.Load(path);

                switch (nvc["active"])
                {
                    case "0":
                        Add(linkDom, nvc["title"], nvc["href"]);
                        break;
                    case "1":
                        Rename(linkDom, nvc["idx"], nvc["title"], nvc["href"]);
                        break;
                    case "2":
                        Remove(linkDom, nvc["idx"]);
                        break;
                    default:
                        break;
                }
                linkDom.Save(path);
            }
            else
            {
                Function.ClientAlert(StringResource.GetField("authfaild"));
            }
        }

        private void Add(XmlDocument linkDom, string title, string href)
        {
            XmlElement link = linkDom.CreateElement("a");
            link.SetAttribute("href", href);
            link.InnerText = title;

            linkDom.DocumentElement.SelectSingleNode("body").AppendChild(link);
        }

        private void Rename(XmlDocument linkDom, string idx, string title, string href)
        {
            XmlElement link = (XmlElement)linkDom.DocumentElement.SelectSingleNode("body").ChildNodes[Int32.Parse(idx)];
            link.SetAttribute("href", href);
            link.InnerText = title;
        }

        private void Remove(XmlDocument linkDom, string idx)
        {
            XmlNode link = linkDom.DocumentElement.SelectSingleNode("body").ChildNodes[Int32.Parse(idx)];
            link.ParentNode.RemoveChild(link);
        }
    }
}